<?php
/* {
Citru - www.citru.se
See license.txt for copyright and license information.
} */

if(!defined("_CITRU")) {die('This file should not be accessed directly.');}
require_once 'Module.php';

class NavigationModule extends Module {
	
	protected $moduleTabs = array("view", "edit", "", "permissions");
	protected $moduleName = "NavigationModule";
	protected $instanceName;
	protected $dbModule;
	protected $permissions;
	
	function __construct($instance, $db_module, $permissions) {
		$this->instanceName = $instance;
		$this->dbModule = $db_module;
		$this->permissions = $permissions;
	}

	/**
	 * Adds the necessary table for TextModule
	 *
	 * @return void
	 */
	public function installTables() {
		// Create table
		$params = array(	"table" => 'NavigationModule',
							"columns" => array( array('id', 'int(11) NOT NULL auto_increment'),
							 					array('instance', 'text NOT NULL'),
												array('name', 'text NOT NULL'),
												array('url', 'text NOT NULL')),
							"primary_key" => 'id');
		if(!$this->dbModule->addTable($params)) {
			throw new Exception('Could not create table for '.$this->moduleName.'.');
		}
		
		// Add global permissions
		$params_perm = array(	'table' => 'Permissions',
        						'set' => array(	'module'=>$this->moduleName,
								'permissions'=>"view=@admin\nedit=@admin\npermissions=@admin"));
        if(!$this->dbModule->insertRow($params_perm)) {
			throw new Exception('Could not create global permissions for '.$this->moduleName.'.');
		}
	}
	
	
	/**
	 * Returns a navigation in the form of a list
	 * The view is what visitors will see.
	 * The link is removed for the list-item referring to the current page.
	 * 
	 * @return 		html for the navigation
	 */
	public function getView() {
		if($this->permissions['view'] != true) { return ''; }
		
		// Find this instances row in the db
		$rows = $this->findInstance();
		if(!$rows) { return "<p>Instance not found!</p>"; }
		
		$url = split("\n", $rows['url']);
		$name = split("\n", $rows['name']);
		
		// Generate a list that is the navigation from the row
		$return = "<ul>\n";
		$url_count = count($url);
		$pageName = $this->getPageName();
		for ($i=0; $i < $url_count; $i++) {
			if($pageName == $this->stripSlash($url[$i])){
				$return .= "\t".'<li id="nav_'.strtolower($name[$i]).'" class="selected">'.$name[$i]."</li>\n";
			} else {
				$return .= "\t".'<li id="nav_'.strtolower($name[$i]).'"><a href="'.$url[$i].'">'.$name[$i]."</a></li>\n";
			}
		}
		$return .= "</ul>";
		
		return $return;
	}

	
	/**
	 * Returns the selected tab of the admin view
	 *
	 * @param string $tab 		name of tab/view to return
	 * @return string			html for selected tab
	 */
	protected function getAdminTab($tab="view") {
		switch($tab) {
			case "edit":
				return $this->getEditForm($message);
			case "permissions":
				return $this->getPermissionsForm();
			default:
				return $this->getView();
		}
	}

	
	/**
	 * Returns a edit-form for the TextModule instance
	 *
	 * @param string $message 		optional, message to display at the end of the form
	 * @return string				html for the edit form
	 */
	private function getEditForm($message="") {
		if($this->permissions['edit'] != true) { return ''; }
		
		// Check if the form should be saved first
		if($_POST['instance'] == "NavigationModule_$this->instanceName" && $_POST['action'] == "edit") {
			if($_POST['new'] == "true") {
				$message = $this->saveFormData(true);
			} else {
				$message = $this->saveFormData(false);
			}
		}
		
		// Get the form data, generate if instance can't be found
		$rows = $this->findInstance();
		$new = 'false';
		if(!$rows) { 
			$rows = array("name"=>"This navigation is empty",
						  "url"=>"Add some menu items and click save" );
			$new = 'true';
		}

		$url = split("\n", $rows['url']);
		$name = split("\n", $rows['name']);

		$elements = array(array('form_start'),
						  array('hidden_instance'),
						  array('hidden_action', 'value'=>'edit'),
						  array('hidden_new', 'value'=>$new),
						  array('label', 'for'=>'name_0', 'text'=>'Name:', 'class'=>'citru_half_width'),
						  array('label', 'for'=>'url_0', 'text'=>'Url:', 'class'=>'citru_half_width', 'after'=>'<br />'));

		for($i=0; $i < count($url)+1; $i++) {
			$elements[] = array('input_text', 'name'=>'name_'.$i, 'value'=>$name[$i], 'class'=>'citru_half_width');
			$elements[] = array('input_text', 'name'=>'url_'.$i, 'value'=>$url[$i], 'class'=>'citru_half_width citru_last_in_row', 'after'=>'<br />');
		}
		
		$elements[] = array('footer_start');
		$elements[] = array('custom', 'data'=>$message);
		$elements[] = array('submit', 'value'=>'Save', 'icon'=>'save');
		$elements[] = array('footer_end');
		$elements[] = array('form_end');
		
		$form = $this->generateForm($elements);
		return $form;
	}	
	
	/**
	 * Updates a previous instance from form data
	 *
	 * @param boolean $new 			true if a new row should be created for the data first
	 * @return string				a message of how things went
	 */
	private function saveFormData($new = false) {
		if($new == true) { $this->createDataRow(); }
		
		$names = array();
		$urls = array();
		for($i=0; isset($_POST['name_'.$i]); $i++) {
			if($_POST['name_'.$i] != "" || $_POST['url_'.$i] != "") {
				$names[] = $_POST['name_'.$i];
				$urls[] = $_POST['url_'.$i];
			}
		}
		
		$name = implode("\n", $names);
		$url = implode("\n", $urls);
		$params = array(	"table" => "NavigationModule",
							"condition" =>	array(
											array( "instance", "=", $this->instanceName, "" ) ),
							"set" => array( 	"name" => $name,
												"url" => $url ));
																	
		$result = $this->dbModule->updateRow($params);
		
		return '<p class="citru_event">Form data saved.</p>';
	}
	
	
	/**
	 * Gives a row from the database with the data for an instance
	 *
	 * @return array 				an array of names and urls for the current instance
	 */
	private function findInstance() {
		$params = array(	"table" => "NavigationModule",
							"columns" => "name, url",
							"condition" =>	array(
											array( "instance", "=", $this->instanceName, "" ) ));
		
		$rows = $this->dbModule->findFirst($params);
		return $rows;
	}
	
	
	
	/**
	 * Takes an array and returns a string of keys and values with glue inbetween
	 *
	 * @param array $array 			array to glue into a string
	 * @param string $inglue 		between key and value
	 * @param string $outglue 		between two elements
	 * @return string				glued string
	 */
	private function implode_with_key($array, $inglue = '=', $outglue = '&') {
	    $return = '';
	    foreach ($array as $key => $val) {
	        $return .= $outglue . $key . $inglue . $val;
	    }
	    return substr($return,strlen($outglue));
	}
	
	
	/**
	 * Returns the name of the current page. ex: index.php
	 *
	 * @return string				page name
	 */
	private function getPageName() {
		// Strip stuff after ? and heading slash
		$url = split("[?]", $_SERVER['REQUEST_URI']);
		// Add back the ?page=
		foreach ($url as $u) {
			if(substr($u, 0, 5) == 'page=') {
				$page = '?'.$u;
				break;
			}
		}
		$url = substr($url[0], 1);
		$url = $url.$page;
		return $url;
	}
	
	/**
	 * Trims a string and then removes the first character if its a slash
	 *
	 * @param string $string	string to strip leading slash from
	 * @return string			string without leading slash	
	 */
	private function stripSlash($string) {
		$string = trim($string);
		if(substr($string, 0, 1) == '/') {
			return substr($string, 1);
		}
		return $string;
	}
	
}

?>
